public class HashBuck {
    static class Node {
        public int key;
        public int val;
        Node next;
        public Node(int key,int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public double loadFactor = 0.75;
    public int usedSize;
    public HashBuck() {
        array = new Node[10];
    }
    public void put(int key,int val) {
        int index = key % array.length;
        Node cur = array[index];
        //1.遍历链表，查看是否存在当前值
        while (cur != null){
            if (cur.key == key){
                //key一样更新val
                cur.val = val;
                return;
            }
            cur = cur.next;
            //2.头插
            Node node = new Node(key, val);
            node.next = array[index];
            array[index] = node;
            usedSize++;
        }
        //3.
        if (LoadFactorcount() > loadFactor) {
            //扩容
            //重新哈希
            resize();
        }
    }
    private double LoadFactorcount() {
        //负载因子计算
        return usedSize * 1.0 / array.length;
    }
    private void resize() {
        Node[] newarray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            //遍历链表
            while(cur != null) {
                Node curN = cur.next;
                int newIndex = cur.key % newarray.length;
                cur.next = array[newIndex];
                newarray[newIndex] = cur;
                cur = cur.next;
                cur = curN;
            }
        }
        array = newarray;
    }
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        //1.遍历链表，查看是否存在当前值
        while (cur != null){
            if (cur.key == key){
                //key一样更新val
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
